home *** CD-ROM | disk | FTP | other *** search
- Path: newsroom.hitc.com!usenet
- From: Chris Ruegger <cruegger@eos.hitc.com>
- Newsgroups: comp.lang.c++
- Subject: virtual operator==(), operator=()
- Date: Fri, 23 Feb 1996 14:32:12 -0500
- Organization: Hughes Information Technology Corporation
- Message-ID: <312E163C.36ED@eos.hitc.com>
- NNTP-Posting-Host: rainman.hitc.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; SunOS 5.4 sun4m)
-
- Forgive what is probably a FAQ, but what is the consensus on
- solving this problem:
-
- I have a class hierarchy. I maintain some eollection of pointers
- to the *BASE* class. Suppose I create a new derived objects and
- I want to find out if it is logically already in my collection,
- using operator==()
-
- It would seem one is forced to make operator==() virtual, check
- the type of the object in the parameter list, and downcast
- appropriately if the two objects are of the same type, and then
- perform the necessary operator==() logic. That is:
-
- class BASE {
- public:
- BASE()
- virtual int operator==(const BASE& base)
- { logic omitted }
- private:
- int foo_;
-
- class DERIVED1 : public BASE {
- public:
- virtual int operator==(const BASE& base)
- { if (*this and base are of the same type)
- DERIVED1& r = *(DERIVED1*)&base; // downcast
- // now compare corresponding data members using r
- }
- return as appropriate
- }
- };
-
- class DERIVED2 : public BASE {
- public:
- virtual int operator==(const BASE& base)
- { if (*this and base are of the same type)
- DERIVED2& r = *(DERIVED2*)&base; // downcast
- // now compare corresponding data members using r
- }
- return as appropriate
- }
- };
-
-
- int main()
- {
-
- // Build a pre-existing list for demonstration purposes
-
- BASE *list[3];
- DERIVED1 d1;
- DERIVED2 d2;
- list [0] = &d1;
- list [1] = &d2;
-
- // Now suppose we build a new object, want to see if it's already
- // in the list
- DERIVED2 d3;
- for (int i = 0; i < 2; i++) {
- if (*list[i] == d3) { // Here we go
- //duplicate found
- }
- }
-
-
- IS there a more elegant way to do this???
- How have others solved this problem?
-
-
- Thanks.
-
-
-
- --------------------------------------------------------------------
- Christopher Ruegger phone: (301) 925-1164
- Email: cruegger@eos.hitc.com
- car@access.digex.com
-